﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace Light.Utility
{
    /// <summary>
    /// 摘要:
    /// 　　指示一个属性可用于排序。
    /// </summary>
    [Serializable]
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    [ComVisible(true)]
    public sealed class SortableAttribute : Attribute, IComparable<SortableAttribute>, IComparer<SortableAttribute>
    {
        private int _index = int.MaxValue;
        private bool _sortable = true;
        private string _displayName;

        /// <summary>
        /// 初始化新实例
        /// </summary>
        public SortableAttribute()
            : base()
        {
        }

        /// <summary>
        /// 初始化新实例
        /// </summary>
        /// <param name="index">序号</param>
        public SortableAttribute(int index)
            : base()
        {
            this.Index = index;
        }

        /// <summary>
        /// 序号
        /// </summary>
        public int Index
        {
            get { return this._index; }
            set { this._index = value; }
        }

        /// <summary>
        /// 是否可用于排序
        /// </summary>
        public bool Sortable
        {
            get { return this._sortable; }
            set { this._sortable = value; }
        }

        /// <summary>
        /// 显示名称
        /// </summary>
        public string DisplayName
        {
            get { return this._displayName; }
            set { this._displayName = value; }
        }

        #region IComparable 成员

        public int CompareTo(object obj)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IComparer<SortableAttribute> 成员

        public int Compare(SortableAttribute x, SortableAttribute y)
        {
            if (Object.ReferenceEquals(x, y))
                return 0;

            if (x == y)
                return 0;

            if (x == null)
                return -1;

            if (y == null)
                return 1;

            int result = x.Index.CompareTo(y.Index);

            if (result == null)
                result = x.DisplayName.CompareTo(y.DisplayName);

            return result;
        }

        #endregion

        #region IComparable<SortableAttribute> 成员

        int IComparable<SortableAttribute>.CompareTo(SortableAttribute other)
        {
            return Compare(this, other);
        }

        #endregion
    }
}